﻿
using System;
using Dexter.CallContext;
using Dexter.Logger.Contracts;
using Quartz;

namespace Dexter.Scheduler.Quartz.Factory {
	/// <summary>
	/// The implementation of <see cref="Quartz.IJob"/>.
	/// </summary>
	/// <remarks>
	///		This class is used to wrap Dexter jobs (<see cref="IJob"/>) into Quartz job (<see cref="global::Quartz.IJob"/>).
	/// </remarks>
	public class QuartzJobWrapper : global::Quartz.IJob  {
		readonly IJob job;
		readonly IDexterCall dexterCall;
		readonly ILogger logger;

		/// <summary>
		/// Initializes a new instance of the <see cref="QuartzJobWrapper"/> class.
		/// </summary>
		/// <param name="job">The job.</param>
		/// <param name="dexterCall">The dexter call.</param>
		/// <param name="logger">The logger.</param>
		public QuartzJobWrapper ( IJob job , IDexterCall dexterCall , ILogger logger ) {
			this.job = job;
			this.logger = logger;
			this.dexterCall = dexterCall;
		}

		/// <summary>
		/// Called by the <see cref="T:Quartz.IScheduler"/> when a <see cref="T:Quartz.Trigger"/>
		///             fires that is associated with the <see cref="T:Quartz.IJob"/>.
		/// </summary>
		/// <remarks>
		/// The implementation may wish to set a  result object on the 
		///             JobExecutionContext before this method exits.  The result itself
		///             is meaningless to Quartz, but may be informative to 
		///             <see cref="T:Quartz.IJobListener"/>s or 
		///             <see cref="T:Quartz.ITriggerListener"/>s that are watching the job's 
		///             execution.
		/// </remarks>
		/// <param name="context">The execution context.</param>
		public void Execute ( JobExecutionContext context ) {
			try {
				if (job.AutoManageSession) {
					dexterCall.StartSession ( );
					job.Execute ( );
					dexterCall.Complete ( true );
					return;
				}

				job.Execute ( );
			}
			catch ( Exception e ) {
				if (job.AutoManageSession) {
					dexterCall.Complete ( false );
				}

				logger.Error ( e.Message, e );
			}
		}
	}
}
